//
//  LastLevelMedicineController.swift
//  YiYaoHui
//
//  Created by 高永效 on 15/12/3.
//  Copyright © 2015年 EgeTart. All rights reserved.
//


//别名的controller: “药品列表”controlle
import UIKit
import Alamofire
import MBProgressHUD

class LastLevelMedicineController: UIViewController {
    
    
    @IBOutlet weak var lastLevelTableView: UITableView!
    @IBOutlet weak var titleItme: UINavigationItem!
    
    var medicineType = ""
    var medicineParentID = ""
    
    
    
    let db = MedicineDB.sharedInstance()
    var lastLevelMedicines = [Medicine]()
    
    //企业请求的
    var forthMedicineID : String!
    var enterpriseID: String!
    var enterpriseLastMedicines = [LastLevelMedicine]()//展开的二级
    var id = 0 //2为请求传值跳转
    var enterpriseType = 6 //中药3；西药4 ;6 随便定的初始化

    override func viewDidLoad() {
        super.viewDidLoad()
        if self.id == 2 {
            getLastLevelMedicines()
            let detailController  = self.storyboard?.instantiateViewControllerWithIdentifier("MedicineDetailController") as! MedicineDetailController
            detailController.enterpriseMedicineType = self.enterpriseType
        }
        else {
            if medicineType == "西药" {
                getDataFromWestMedicines()
            }
            else {
                getDataFromChineseMedicines()
            }
        }
        lastLevelTableView.tableFooterView = UIView(frame: CGRectZero)
    }
    
    
    func getDataFromChineseMedicines() {
        db.open()
        
        if let fourthLevelMedicineID = db.executeQuery("select id from medicine_type where parent_type_id = ?", medicineParentID) {
            while fourthLevelMedicineID.next() {
                let medicineTypeId = fourthLevelMedicineID.stringForColumn("id")
                if let lastLevelResults = db.executeQuery("select id, name from chinese_medicine where medicine_type_id = ?", medicineTypeId) {
                    while lastLevelResults.next() {
                        let id = lastLevelResults.stringForColumn("id")
                        let name = lastLevelResults.stringForColumn("name")
                        let medicine = Medicine(name: name, id: id)
                        lastLevelMedicines.append(medicine)
                    }
                }
            }
        }
        db.close()
    }
    
    func getDataFromWestMedicines() {
        db.open()

        if let lastLevelResults = db.executeQuery("select id, name from west_medicine where medicine_type_id = ?", medicineParentID) {
            while lastLevelResults.next() {
                let id = lastLevelResults.stringForColumn("id")
                let name = lastLevelResults.stringForColumn("name")
                let medicine = Medicine(name: name, id: id)
                lastLevelMedicines.append(medicine)
            }
        }
        db.close()
    }
    
    //请求药品名和别名 ： forth level medicine data
    func getLastLevelMedicines() {
            let lastLevelURL = "http://112.74.131.194:8080/MedicineProject/App/user/getEnterMedicines"
            
            Alamofire.request(.POST, lastLevelURL, parameters: ["enterpriseId": enterpriseID,"medicineTypeId":forthMedicineID], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (_, _, result) -> Void in
                if let value = result.value {
                    if let lastMedicine = value["EnterWestMedicines"] as? [Dictionary<String, AnyObject>] {
                        for item in lastMedicine {
                            let enterpriseLastMedicine = LastLevelMedicine(enterpristLevelMedicine:item)
                            self.enterpriseLastMedicines.append(enterpriseLastMedicine)
                        }
                    }
                    NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                        self.lastLevelTableView.reloadData()
                        MBProgressHUD.hideHUDForView(self.view, animated: true)
                    })
                }
                else {
                    //MARK: something error
                }
        }
    }
}

extension LastLevelMedicineController: UITableViewDataSource {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.id == 2 {
            return enterpriseLastMedicines.count
        } else {
            return lastLevelMedicines.count
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("lastLevelCell", forIndexPath: indexPath)
        
        if self.id == 2 {
            cell.textLabel?.text = enterpriseLastMedicines[indexPath.row].lastLevelName + "   " + enterpriseLastMedicines[indexPath.row].lastLevelOtherName
        } else {
            cell.textLabel?.text = lastLevelMedicines[indexPath.row].name
        }
        return cell
    }
}

extension LastLevelMedicineController: UITableViewDelegate {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let medicineDetailController = storyboard?.instantiateViewControllerWithIdentifier("MedicineDetailController") as! MedicineDetailController
        
        if self.id == 2 {
            let medicineName = enterpriseLastMedicines[indexPath.row].lastLevelName
            medicineDetailController.medicineID = enterpriseLastMedicines[indexPath.row].lastLevelID
            medicineDetailController.id = self.id
            medicineDetailController.enterpriseMedicineType = self.enterpriseType
            medicineDetailController.medicineName = medicineName
        } else {
            let medicineName = lastLevelMedicines[indexPath.row].name
            medicineDetailController.medicineID = lastLevelMedicines[indexPath.row].id
            medicineDetailController.medicineType = medicineType
            medicineDetailController.medicineName = medicineName
        }
        titleItme.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(medicineDetailController, animated: true)
        self.hidesBottomBarWhenPushed = false
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
}

